package gepes.dao;

import gepes.exepcion.DAOExcepcion;
import gepes.modelo.SubCategoria;
import gepes.util.ConexionBD;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class SubCategoriaDAO extends BaseDAO{
	
	public SubCategoria insertar(SubCategoria sc) throws DAOExcepcion {
		String query = "insert into subcategoria(nombre,descripcion,codcategoria)"
				+ "values(?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.ConectarDB();
			stmt = con.prepareStatement(query);
			stmt.setString(1, sc.getNombre());
			stmt.setString(2,sc.getDescripcion());
			stmt.setInt(3, sc.getCodcategoria().getCodCategoria());
			
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("Error insertar");
			}

			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			sc.setCodsubcategoria(id);
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return sc;
	}

}
